<template>
    <div class="container">
        <div class="header">
            <el-button type="primary" size="mini" @click="refreshStatic">刷新</el-button>
            <el-button type="primary" size="mini" @click="queryStatic">查询</el-button>
            <el-button type="primary" size="mini" v-authCode.show="B_0153" @click="loadout">导出</el-button>
            <el-button type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
        </div>
        <div class="dataInfo">
            <div style="height: calc(100vh - 210px)">
                <vxe-table
                    auto-resize
                    height="100%"
                    border
                    stripe
                    ref="xTable"
                    resizable
                    :data="tableDataResult"
                    @checkbox-all="selectAllValueEvent"
                    @checkbox-change="selectValueChangeEvent"
                    @sort-change="handleSort"
                    :sort-config="{
                        multiple: true,
                        defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                        remote: false,
                    }"
                    highlight-hover-row
                    :key="tableDataResultNumKey + 'tableDataResultNumKey'"
                    v-loading="tableDataResultLoading"
                    header-align="center"
                    show-header-overflow
                    show-overflow
                    @resizable-change="resizeChange"
                >
                    <vxe-table-column type="checkbox" min-width="40" fixed="left"></vxe-table-column>
                    <vxe-column
                        v-for="item in showFieldList"
                        :fixed="item.type === 'btn' ? (item.fixed ? item.fixed : 'right') : ''"
                        :key="item.id"
                        :width="item.width || ''"
                        :min-width="item.minWidth || '100'"
                        :title="item.content"
                        :field="item.id"
                        :sortable="!['reportCode', 'reportName', 'marketName', 'dictBankCodes', 'intervalRange'].includes(item.id)"
                        header-align="center"
                        :align="getAlign(item)"
                    >
                        <template #default="{ row }">
                            <span v-if="item.type == 'func'">
                                {{ item.funcBody(row[item.id], row) || '--' }}
                            </span>
                            <span v-else-if="item.type == 'statusTag'">
                                <StatusTag :code="row[item.id]"></StatusTag>
                            </span>
                            <span v-else-if="item.type == 'status'">
                                {{ item.statusKV[row[item.id]] }}
                            </span>
                            <span v-else-if="item.type == 'date'">
                                {{ dateFormat(row[item.id]) || '--' }}
                            </span>

                            <a v-else-if="item.id == 'entryName'" href="javascript:;" @click="jumpToRoute(row)">{{ row.entryName }}</a>

                            <span v-else-if="item.id == 'dictStockCodes'" :key="fieldKey + 'dictStockCodes'">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1">
                                        <div v-for="(item, index) in row.dictStockCodes" :key="index">
                                            {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                        </div>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1" style="cursor: default">
                                        {{ row.dictStockCodes.length + '个证券' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 1">
                                    {{ row.dictStockCodes[0].dictKey + '(' + row.dictStockCodes[0].dictKeyName + ')' }}
                                </span>
                                <span
                                    v-if="
                                        !row.hasOwnProperty('dictStockCodes') ||
                                        (row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 0)
                                    "
                                >
                                    --
                                </span>
                            </span>

                            <span v-else-if="item.id == 'dictPtStockCodes'" :key="fieldKey + 'dictPtStockCodes'">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('dictPtStockCodes') && row.dictPtStockCodes.length > 1">
                                        <div v-for="(item, index) in row.dictPtStockCodes" :key="index">
                                            {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                        </div>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('dictPtStockCodes') && row.dictPtStockCodes.length > 1" style="cursor: default">
                                        {{ row.dictPtStockCodes.length + '个证券' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('dictPtStockCodes') && row.dictPtStockCodes.length === 1">
                                    {{ row.dictPtStockCodes[0].dictKey + '(' + row.dictPtStockCodes[0].dictKeyName + ')' }}
                                </span>
                                <span
                                    v-if="
                                        !row.hasOwnProperty('dictPtStockCodes') ||
                                        (row.hasOwnProperty('dictPtStockCodes') && row.dictPtStockCodes.length === 0)
                                    "
                                >
                                    --
                                </span>
                            </span>
                            <span v-else-if="item.id == 'dictBankCodes'" :key="fieldKey + 'dictBankCodes'">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('dictBankCodes') && row.dictBankCodes.length > 1">
                                        <div v-for="(item, index) in row.dictBankCodes" :key="index">
                                            {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                        </div>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('dictBankCodes') && row.dictBankCodes.length > 1" style="cursor: default">
                                        {{ row.dictBankCodes.length + '个银行' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('dictBankCodes') && row.dictBankCodes.length === 1">
                                    {{ row.dictBankCodes[0].dictKey + '(' + row.dictBankCodes[0].dictKeyName + ')' }}
                                </span>
                                <span
                                    v-if="
                                        !row.hasOwnProperty('dictBankCodes') ||
                                        (row.hasOwnProperty('dictBankCodes') && row.dictBankCodes.length === 0)
                                    "
                                >
                                    --
                                </span>
                            </span>
                            <span v-else-if="item.id == 'branchValues'" :key="fieldKey + 'branchValues'">
                                <el-tooltip placement="bottom">
                                    <div slot="content" v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1">
                                        <div v-for="(item, index) in row.branchValues" :key="index">
                                            {{ item.replace(/(\.|\d+)$/, $1 => numberFormatCIB($1)) }}
                                        </div>
                                    </div>
                                    <el-tag v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1" style="cursor: default">
                                        {{ row.branchValues.length + '个分支' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('branchValues') && row.branchValues.length === 1">{{
                                    row.branchValues[0].replace(/(\.|\d+)$/, $1 => numberFormatCIB($1))
                                }}</span>
                            </span>
                            <span v-else-if="item.id == 'investBalance'" :key="fieldKey + 'investBalance'">
                                <span v-if="!row.investBalance || !row.investBalance.trim()"></span>
                                <el-popover
                                    v-else-if="getObjectLength(JSON.parse(row.investBalance)) && getObjectLength(JSON.parse(row.investBalance)) > 1"
                                    placement="top"
                                    trigger="hover"
                                >
                                    <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in JSON.parse(row.investBalance)" :key="key">
                                        {{ '阀值' + ++index + '可投余量: ' + JSON.parse(row.investBalance)['INVESTABLE_BALANCE_' + index] }}
                                    </div>
                                    <el-tag slot="reference">{{ getObjectLength(JSON.parse(row.investBalance)) + '个可投余量' }}</el-tag>
                                </el-popover>
                                <span v-else v-for="(value, key) in JSON.parse(row.investBalance)" :key="key">{{ value }}</span>
                            </span>

                            <span
                                v-else-if="item.id == 'prohibitionDate'"
                                :key="fieldKey + 'investBalance'"
                                :style="prohibitionDateColor(row.prohibitionDate)"
                            >
                                {{ row.prohibitionDate > -1 ? row.prohibitionDate + '天' : '0' }}
                            </span>

                            <span v-else>
                                {{ row[item.id] === 0 || (row[item.id] && (row[item.id] + '').trim()) ? row[item.id] : '--' }}
                            </span>
                        </template>
                    </vxe-column>
                    <vxe-table-column title="操作" show-overflow min-width="180" fixed="right" align="center">
                        <template #default="{ row }">
                            <RiskIconButton type="primary" topTitle="详情" icon="el-icon-view" @on-click="handleRowOperateLook(row)"></RiskIconButton>
                            <RiskIconButton
                                icon="el-icon-data-analysis"
                                type="primary"
                                topTitle="走势图"
                                @on-click="handleRowOperateChart(row)"
                                v-if="showParamByDocking('FSCINDA')"
                            ></RiskIconButton>
                            <!-- <RiskIconButton
                                icon="el-icon-brush"
                                type="primary"
                                topTitle="计算因子拆解图"
                                @on-click="handleRowOperateDecomposeCalc(row)"
                            ></RiskIconButton> -->
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </div>
            <RiskPagination :paging="page" @page-change="pageQuery"></RiskPagination>
        </div>
        <StaticResultSearch
            :staticResultQueryDialogVO="staticResultQueryDialogVO"
            :reqVO="staticResultReqVO"
            @staticResultQueryReturn="staticResultQueryReturn"
            :editableTabsValue="activeValue"
            :showErrorType="showErrorType"
        >
        </StaticResultSearch>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="activeValue === 'first' ? columns : historyColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :table-name="activeValue === 'first' ? 'RISK_RES' : 'RISK_RESULT_H'"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import Dict from '../dict/index';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import StaticResultDetail from './static-result-detail.vue';
import StaticResultSearch from './static-result-search.vue';
import {
    numberFormat,
    unitShow,
    dateFormat,
    thousandsFormat,
    timeFormat,
    getConfigItem,
    numberFormatXDAY,
    jumpRouter,
    numberFormatCIB,
} from '@/utils/tools';
import ColumnUtil from '@/pages/risk-time/utils/column-util';
import { downLoadFile } from '@/utils/request';
import { getTableLayout, getTableLayout2, updateTableLayout } from '@/common/api/commonApi';
import { DialogVO } from '@yhfin/biz';
import { getSystem } from '@/utils/user-util';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({
    name: 'RiskResultTab',
    components: {
        RiskIconButton,
        StaticResultSearch,
        StaticResultDetail,
        StatusTag,
        BranchTag,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class RiskResultTab extends Vue {
    @Prop() activeValue: string;
    @Prop() assetList: any;
    @Prop() fdAcList: any;

    numberFormat = numberFormat;
    numberFormatCIB = numberFormatCIB;
    unitShow = unitShow;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    sortProp: string = 'triggerType';
    sortOrder: string = 'desc'; // 排序方式

    private page: any = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    showErrorType: boolean = false; // 是否展示错误类型
    private tableDataResultLoading: boolean = false; // 静态结果加载

    // 静态结果请求参数
    private staticResultReqVO: any = {
        calculateDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        calculateDateStart: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        entryCodes: '',
        entryGroups: [],
        entryKey: '',
        entryNames: [],
        excludeEntryGroup: false,
        fundGroups: [],
        paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 50 },
        prohibitionDate: '',
        reBankCode: '',
        reFundCode: '',
        reIssueCode: '',
        reStockCode: '',
        resultId: '',
        showNewRecord: '1',
        tradeDateStart: '',
        tradeDateEnd: '',
        triggerTypeList: ['3'],
        precision: false,
        sort: '',
        fundTypes: [],
        fdProductCodes: [],
        // entryNameOr: true,
    };

    // 结果查询参数
    sortParamObj = {
        resultId: 'N_RESULT_ID',
        tradeDate: 'D_TRADE_DATE',
        calculateDate: 'D_CAL_DATE',
        dictFundCodes: 'C_FUND_CODES',
        triggerType: 'C_TRIGGER_TYPE',
        entryName: 'C_ENTRY_NAME',
        result: 'N_RESULT',
        prohibitionDate: 'N_PROHIBITION_DATE',
        triggerDay: 'N_TRIGGER_DAY',
        dictStockCodes: 'LENGTH(C_STOCK_CODES)',
        dictPtStockCodes: 'LENGTH(C_PT_STOCK_CODES)',
        branchValues: 'C_BR_VALUES',
        compareType: 'C_COMPARE_TYPE',
        thresholdValue: 'N_THRESHOLD_VALUE',
        resultInformation: 'length(C_OUTCOME_INFORMATION)',
        investBalance: 'C_INVEST_BALANCE',
        assetCodes: 'LENGTH(C_ASSET_CODES)',
        fdAcCodes: 'LENGTH(C_FD_AC_CODES)',
        errorMessage: 'C_ERROR_MESSAGE',
        fdProductCode: 'C_FUND_CODES',
        fundType: 'C_FUND_TYPE',
        numerator: 'N_NUMERATOR',
        denominator: 'N_DENOMINATOR',
        controlGrade: 'C_CONTROL_GRADE',
        frequency: 'N_FREQUENCY',
        fundCode: 'C_FUND_CODES',
        fundName: 'C_FUND_CODES',
    };
    historySortColumns = ['tradeDate', 'calculateDate', 'triggerType', 'entryName', 'entryCode', 'prohibitionDate'];

    // 历史结果参数
    historyColumns: any = [
        {
            id: 'tradeDate',
            content: '估值日期',
            type: 'date',
            align: 'center',
            minWidth: 120,
        },
        {
            id: 'calculateDate',
            content: '计算日期',
            type: 'func',
            funcBody: (value, row) => dateFormat(row['calculateDate']) + '\n' + timeFormat(row['calculateTime']),
            align: 'center',
            minWidth: 160,
        },
        {
            id: 'dictFundCodes',
            content: '产品代码(名称)',
            minWidth: 160,
            type: 'func',
            funcBody: value => this.formatDictFundCodes(value),
        },
        {
            id: 'assetCodes',
            content: '资产单元编号(名称)',
            show: this.SHOW_SECURITY,
            minWidth: 170,
            type: 'func',
            funcBody: value => this.formatAssetCodes(value),
        },
        {
            id: 'fdAcCodes',
            content: '组合编码(名称)',
            show: this.SHOW_SECURITY,
            minWidth: 160,
            type: 'func',
            funcBody: value => this.formatFdAcCodes(value),
        },
        {
            id: 'triggerType',
            content: '触警类型',
            type: 'statusTag',
        },
        {
            id: 'entryCode',
            content: '条目编号',
        },
        {
            id: 'entryName',
            content: '风险说明',
            minWidth: 120,
        },
        {
            id: 'result',
            content: '计算结果(单位)',
            type: 'func',
            funcBody: (value, row) => {
                return row.result != undefined ? numberFormatCIB(row.result, row.unit) + unitShow(row.unit) : '--';
            },
            minWidth: 140,
        },

        {
            id: 'errorMessage',
            content: '计算错误信息',
            minWidth: 160,
            show: this.showErrorType,
        },
        {
            id: 'prohibitionDate',
            content: '连续违规天数',
            align: 'right',
            // type: 'func',
            // funcBody: (value, row) => (row.prohibitionDate > -1 ? row.prohibitionDate + '天' : '0'),
            minWidth: 140,
        },
        {
            id: 'triggerDay',
            content: '连续触警天数',
            align: 'right',
            type: 'func',
            funcBody: (value, row) => (row.triggerDay > -1 ? row.triggerDay + '天' : ''),
            minWidth: 140,
        },
        {
            id: 'dictStockCodes',
            content: '证券代码(名称)',
            minWidth: 140,
        },
        {
            id: 'dictPtStockCodes',
            content: '穿透证券代码(名称)',
            minWidth: 140,
        },
        {
            id: 'reportCode',
            content: '证券代码',
            minWidth: 140,
        },
        {
            id: 'reportName',
            content: '证券名称',
            minWidth: 140,
        },
        {
            id: 'marketName',
            content: '交易市场',
            minWidth: 140,
        },
        {
            id: 'dictBankCodes',
            content: '存款银行名称',
            minWidth: 140,
        },
        {
            id: 'fdProductCode',
            content: '基金代码',
            minWidth: 140,
        },
        {
            id: 'fundType',
            content: '产品类型',
            minWidth: 140,
        },
        {
            id: 'branchValues',
            content: '分支值',
            minWidth: 140,
        },
        {
            id: 'numerator',
            content: '分子值',
            minWidth: 140,
            type: 'func',
            funcBody: (value, row) => numberFormatCIB(value),
        },
        {
            id: 'denominator',
            content: '分母值',
            minWidth: 140,
            type: 'func',
            funcBody: (value, row) => numberFormatCIB(value),
        },
        {
            id: 'compareType',
            content: '条目比较方向',
            type: 'status',
            statusKV: Dict.CompareDirection,
            minWidth: 140,
        },
        {
            id: 'thresholdValue',
            content: '条目触发值',
            type: 'func',
            funcBody: (value, row) =>
                row.thresholdValue != undefined ? numberFormatCIB(row.thresholdValue, row.unit, 'thresholdValue') + unitShow(row.unit) : '--',
            minWidth: 120,
        },
        {
            id: 'investBalance',
            content: '可投余量',
            align: 'right',
            minWidth: 130,
        },
        {
            id: 'frequency',
            content: '触发频率次数',
            minWidth: 140,
        },
        {
            id: 'controlGrade',
            content: '风险等级',
            minWidth: 120,
            align: 'center',
            type: 'func',
            funcBody: (value, row) => DictionConstUtil.ControlGrade[value] || '--',
        },
    ];

    columns: any[] = [
        {
            id: 'resultId',
            content: '序号',
        },
        {
            id: 'resultInformation',
            content: '结果信息',
        },
    ];
    private tableDataResult: any[] = []; // 静态结果表数据
    private hasSelectedData: any[] = []; // 静态结果勾选数据

    ColumnUtil = new ColumnUtil();
    private staticResultQueryDialogVO: DialogVO = new DialogVO(); // 查询请求弹框

    // 信达默认导出顺序
    FSCINDAExportColumn: any[] = [
        { id: 'resultId', content: '序号' },
        { id: 'triggerType', content: '触险类型' },
        { id: 'tradeDate', content: '估值日期' },
        { id: 'prohibitionDate', content: '连续违规天数' },
        { id: 'triggerDay', content: '连续预警天数' },
        { id: 'dictFundCodes', content: '产品代码(名称)' },
        { id: 'entryCode', content: '条目编号' },
        { id: 'entryName', content: '风险说明' },
        { id: 'result', content: '计算结果(单位)' },
        { id: 'thresholdValue', content: '条目触发值' },
        { id: 'dictStockCodes', content: '证券代码(名称)' },
        { id: 'dictPtStockCodes', content: '穿透证券代码(名称)' },
        { id: 'branchValues', content: '分支值' },
        { id: 'numerator', content: '分子值' },
        { id: 'denominator', content: '分母值' },
        { id: 'investBalance', content: '可投余量' },
        { id: 'legalDays', content: '法定调整天数' },
        { id: 'insideDays', content: '内部调整天数' },
        { id: 'frequency', content: '触发频率次数' },
        { id: 'controlGrade', content: '风险等级' },
        { id: 'resultInformation', content: '结果信息' },
        { id: 'calculateDate', content: '计算日期' },
    ];
    /** ** 保存列宽 ** **/
    resizeList: any = { entryName: 100, entryCode: 199 };

    /**
     * 列宽拖动 回调
     */
    resizeChange({ column }) {
        let col = {};
        this.$set(col, column.property, column.resizeWidth);

        // this.resizeList = { ...this.resizeList, ...col };
        this.resizeList = Object.assign({}, this.resizeList, col);
        let tableName = this.activeValue == 'second' ? 'RISK_RESULT_H_RESIZE' : 'RISK_RESULT_RESIZE';
        updateTableLayout({ showField: this.resizeList, tableName });
    }

    async created() {
        if (this.WEB_DOCKING === 'HUATAI') {
            // #9815 华泰资产项目，客户提出将风险报告-静态结果、静态历史结果页面中的产品代码（名称）展示列，要求分开展示
            let columns = this.historyColumns;
            await columns.splice(
                2,
                1,
                {
                    id: 'fundCode',
                    content: '产品代码',
                    minWidth: 130,
                    // type: 'func',
                    // funcBody: value => value && value.join(','),
                },
                {
                    id: 'fundName',
                    content: '产品名称',
                    minWidth: 130,
                    // type: 'func',
                    // funcBody: value => value && value.join(','),
                }
            );
            columns.push({
                id: 'intervalRange',
                content: '止损控制区间',
                minWidth: 140,
            });
            this.historyColumns = columns;
        }
    }

    async mounted() {
        await this.getShowErrorType();
        this.historyColumns.forEach(ele => {
            if (ele.id == 'errorMessage') {
                ele.show = this.showErrorType;
            }
        });
        this.historyColumns = this.historyColumns.filter((item: any) => item.show !== false);
        this.columns = this.ColumnUtil.handleColumns(this.columns, 'id', 'resultId', this.historyColumns, true);
        console.log(this.columns, '??');

        if (this.activeValue == 'second') {
            this.resizeList = (await getTableLayout2('RISK_RESULT_H_RESIZE')) || null;
            for (const key in this.resizeList) {
                if (Object.prototype.hasOwnProperty.call(this.resizeList, key)) {
                    const value = this.resizeList[key];
                    // 页大小记忆
                    // if (key === 'pageSize') {
                    //     this.paging.pageSize = value;
                    // } else if (key == 'sortField') {
                    //     this.defaultSort[key] = value;
                    //     this.defaultSort.field = this.resizeList['field'] || '';
                    //     this.defaultSort['order'] = this.resizeList['order'] || '';
                    //     this.searchParams.sort = (value + ' ' + this.defaultSort['order']).trim().toUpperCase();
                    // }
                    // 列宽记忆
                    for (let i = 0; i < this.historyColumns.length; i++) {
                        const element = this.historyColumns[i];
                        if (element.id === key) {
                            element.minWidth = value;
                            break;
                        }
                    }
                }
            }
        } else {
            this.resizeList = (await getTableLayout2('RISK_RESULT_RESIZE')) || null;
            for (const key in this.resizeList) {
                if (Object.prototype.hasOwnProperty.call(this.resizeList, key)) {
                    const value = this.resizeList[key];
                    // 页大小记忆
                    // if (key === 'pageSize') {
                    //     this.paging.pageSize = value;
                    // } else if (key == 'sortField') {
                    //     this.defaultSort[key] = value;
                    //     this.defaultSort.field = this.resizeList['field'] || '';
                    //     this.defaultSort['order'] = this.resizeList['order'] || '';
                    //     this.searchParams.sort = (value + ' ' + this.defaultSort['order']).trim().toUpperCase();
                    // }
                    // 列宽记忆
                    for (let i = 0; i < this.columns.length; i++) {
                        const element = this.columns[i];
                        if (element.id === key) {
                            element.minWidth = value;
                            break;
                        }
                    }
                }
            }
        }
        await this.queryLayout();
        this.pageQuery(1);
    }

    // 查询静态是否展示错误类型
    async getShowErrorType() {
        let values = getSystem() || [];
        if (!getSystem().length) {
            await new Promise((resolve, reject) => {
                this.$axios
                    .get('/systemParam/list')
                    .then((res: any) => {
                        values = res;
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        }
        let param;
        // 静态结果页面是否查询错误类型，1-开启，0-关闭
        param = values.find(item => item.paramKey == 'STATIC_REPORT_IS_ERROR_TYPE')?.paramValue;
        if (!param) {
            this.showErrorType = false;
            return;
        }
        if (param == '0') {
            this.showErrorType = false;
        } else if (param == '1') {
            this.showErrorType = true;
        }
    }

    // 结果分页
    private pageQuery(currentPage?: number): void {
        const url = this.activeValue === 'first' ? '/static/result/list' : '/static/history/result/list';
        this.tableDataResultLoading = true;
        currentPage && (this.page.currentPage = currentPage);
        this.$axios
            .post(url, {
                ...this.staticResultReqVO,
                entryNameOr: this.staticResultReqVO.entryNames.length > 1,
                paging: {
                    currentPage: this.page.currentPage,
                    pageSize: this.page.pageSize,
                },
            })
            .then((res: any) => {
                if (this.showErrorType) {
                    this.tableDataResult = res.list;
                } else {
                    this.tableDataResult = res.list.filter(item => item.triggerType != '4');
                }
                this.page.total = res.total;
                this.tableDataResultLoading = false;
                this.fieldKey++;
            })
            .catch(() => {
                this.tableDataResultLoading = false;
            });
    }

    /**
     * 表头排序(静态结果)
     */
    handleSort(column: any) {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        const sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        let sort = '';
        const property = column.property;
        if (sortType) {
            if (property == 'entryCode') {
                if (sortType == 'DESC') {
                    sort = "DECODE(INSTR(C_ENTRY_CODE,'YH'),1,1,0) DESC,TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) DESC";
                } else {
                    sort = "DECODE(INSTR(C_ENTRY_CODE,'YH'),1,1,0) DESC,TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) ASC";
                }
            } else if (property === 'calculateDate') {
                if (this.activeValue === 'first') {
                    if (sortType == 'DESC') {
                        sort = 'D_CAL_DATE DESC, D_CAL_TIME DESC';
                    } else {
                        sort = 'D_CAL_DATE ASC, D_CAL_TIME ASC';
                    }
                } else {
                    if (sortType == 'DESC') {
                        sort = 'D_CAL_DATE  DESC';
                    } else {
                        sort = 'D_CAL_DATE  ASC';
                    }
                }
            } else {
                sort = this.sortParamObj[property] + ' ' + sortType;
            }
            if (this.historySortColumns.indexOf(property) < 0 && this.activeValue !== 'first') {
                return;
            }
        }
        this.staticResultReqVO.sort = sort;
        this.pageQuery(1);
    }

    // 导出
    private loadout(): void {
        let data = this.hasSelectedData;
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
            // this.$message.warning('请先勾选导出的数据');
            // return;
            data = [];
        }
        // 信达默认导出顺序
        if (this.WEB_DOCKING === 'FSCINDA') {
            this.$confirm('是否下载文件?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
            }).then(() => {
                if (this.activeValue === 'first') {
                    const url = '/static/fscinda/result/export';
                    this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    downLoadFile({
                        url: url,
                        method: 'post',
                        data: { ...this.staticResultReqVO },
                    });
                } else {
                    this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    this.$axios.post('/static/fscinda/history/result/export', { ...this.staticResultReqVO }).then((res: any) => {
                        this.$emit('updateActiveTab', 'third');
                    });
                }
            });
        } else {
            this.$confirm('是否下载文件?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
            }).then(() => {
                if (this.activeValue === 'first') {
                    const url = '/static/result/export';
                    this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    downLoadFile({
                        url: url,
                        method: 'post',
                        data: { ...this.staticResultReqVO, columns: this.showFieldList },
                    });
                } else {
                    //  '/static/history/result/export';
                    this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    this.$axios.post('/static/history/result/export', { ...this.staticResultReqVO, columns: this.showFieldList }).then((res: any) => {
                        this.$emit('updateActiveTab', 'third');
                    });
                }
            });
        }
    }

    // 结果刷新
    private refreshStatic(): void {
        this.hasSelectedData = [];
        this.pageQuery(1);
    }

    // 查询
    private queryStatic(): void {
        const title = this.activeValue == 'first' ? '静态结果高级查询' : '静态历史结果高级查询';
        this.staticResultQueryDialogVO = this.staticResultQueryDialogVO.getAddDialog(title);
    }

    // 高级查询返回值
    private staticResultQueryReturn(val): void {
        this.staticResultReqVO = val;
        this.pageQuery(1);
    }

    // 详情
    private handleRowOperateLook(row): void {
        const isHistory = this.activeValue === 'second';
        this.$emit('handleRowOperateLook', { row, isHistory });
    }

    // 走势图
    private handleRowOperateChart(row): void {
        this.$emit('handleRowOperateChart', row);
    }

    // 计算因子拆解图
    handleRowOperateDecomposeCalc(row) {
        this.$emit('handleRowOperateDecomposeCalc', row);
    }

    // 全选
    private selectAllValueEvent({ selection }): void {
        this.hasSelectedData = selection;
    }

    // 部分勾选
    private selectValueChangeEvent({ selection }): void {
        this.hasSelectedData = selection;
    }

    /* **************************** 布局设置start ***************************** */
    layoutDialog: boolean = false; // 试算结果表布局设置
    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表
    fixedFieldList: any[] = []; // 固定字段列表
    tableDataResultNumKey: number = 1; // 静态结果Key
    fieldKey: number = 1;
    // 获取页面布局信息
    async queryLayout() {
        let url = 'RISK_RES';
        let columns = this.columns;

        if (this.activeValue == 'second') {
            url = 'RISK_RESULT_H';
            columns = this.historyColumns;
        }
        const resList: any = await new Promise((resolve, reject) => {
            getTableLayout(url)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        console.log(resList, 'resList');
        if (resList) {
            let list: any;
            console.log(list, 'list');

            try {
                list = JSON.parse(resList);
            } catch (err) {
                list = resList;
            }
            this.selectedFieldList = [];
            list.forEach(ele => {
                const obj = columns.find(item => item.id == ele.id);
                obj && this.selectedFieldList.push(obj);
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        } else {
            this.showFieldList = columns;
            this.selectedFieldList = columns;
        }
        this.tableDataResultNumKey++;
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    /* **************************** 布局设置END ***************************** */

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    getAlign(ele: any) {
        let obj = this.columns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'left';
    }

    // 格式化产品代码
    private formatDictFundCodes(cellValue): string {
        let valueStr = XEUtils.map(cellValue, item => {
            if (item) {
                return item.dictKey + '(' + item.dictKeyName + ')';
            } else {
                return '--';
            }
        });
        return valueStr.toString();
    }

    formatAssetCodes(cellValue) {
        let retData = [];
        cellValue &&
            cellValue.map(key => {
                let name = (this.assetList.find(item => item.assetCode == key) || {}).assetName;
                retData.push(`${key}(${name})`);
            });
        return retData.toString() || '--';
    }

    formatFdAcCodes(cellValue) {
        let retData = [];
        cellValue &&
            cellValue.map(key => {
                let name = (this.fdAcList.find(item => item.fundAccountCode == key) || {}).fundAccountName;
                retData.push(`${key}(${name})`);
            });
        return retData.toString() || '--';
    }

    // 根据docking来判断是否展示字段
    showParamByDocking(dockingValue: string) {
        let isShow = true;
        const docking = getConfigItem('WEB_DOCKING');
        if (docking === dockingValue) {
            isShow = false;
        }
        return isShow;
    }

    /**
     * #9496 【诺安基金】(功能)静态结果连续违规天数的字体颜色标记
     * @prohibitionDate 连续违规天数
     */
    prohibitionDateColor(prohibitionDate) {
        if (this.WEB_DOCKING !== 'LIONFUND') {
            return;
        }
        if (!prohibitionDate) {
            return;
        }

        if (prohibitionDate === 1) {
            return { color: '#d9001b' };
        } else if (prohibitionDate > 1 && prohibitionDate <= 10) {
            return { color: '#f59a23' };
        }
    }

    jumpToRoute(data): void {
        let msg = {
            title: '投资风险设置',
            path: '/risk/setting/itemSetting',
            type: '0', // 0-内部 1-外部 (内部是指 待跳转页面代码 在这套vue里)
            params: { entryCode: data.entryCode, for: '投资风险设置' }, // string | any 需要带进跳转页面的参数
        };
        // 进行跳转待处理
        jumpRouter(msg);
    }
}
</script>
<style lang="scss" scoped>
// tabs主内容
.container {
    padding: 10px 20px;
    .header {
        padding: 10px;
        border: 1px solid #ccc;
    }
    .dataInfo {
        margin-top: 10px;
        border: 1px solid #ccc;
    }

    a {
        // color: var(--primary);
        // padding: 0 3px;
        text-decoration: none;
    }
}
</style>
<style lang="scss">
.tips-popper {
    max-width: 700px;
    max-height: 300px;
    overflow: auto;
}
</style>
